// pages/goodinfo/goodinfo.js
import { getGoodsInfoApi } from '../../api/goods'
import { addShoppingCartApi, getCartDetailApi, existsInCartApi } from '../../api/cart'
// import Dialog from '@vant/weapp/dialog/dialog'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodId: '',
    goodInfo: {},
    totalPrice: 0,
    tabCount: 1,
    tabState: 0,
    sampleName: '',
    repeatShow: false,
    repeatList: [],
    repeatActiveIndex: -1,
    cartId: undefined,
    cartDetail: {}
  },

  repeatShowhandle() {
    if (this.data.tabCount === 1) {
      wx.showToast({
        title: '没有可复用的样品信息~',
        icon: 'none'
      })
      return
    }
    const repeatList = []
    for (let i = 0; i < this.data.tabCount; i++) {
      const sampleComp = this.selectComponent('#method-item' + i)
      repeatList.push({
        data: sampleComp.data,
        id: i + 1
      })
    }

    this.setData({
      repeatShow: true,
      repeatList
    })
  },

  chooseRepeatHandle(e) {
    const index = e.currentTarget.dataset.index

    this.setData({
      repeatActiveIndex: index
    })
  },

  confirmHandle() {
    const copyData = this.data.repeatList[this.data.repeatActiveIndex].data
    const curComp = this.selectComponent('#method-item' + this.data.tabState)
    const { childResult, isRender, result, countPrice } = copyData
    curComp.setData({ childResult, isRender, result, countPrice }, () => {
      this.computedPrice()
    })
  },

  onClose() {
    this.setData({
      repeatActiveIndex: -1
    })
  },

  /**
   * 获取商品详情
   */
  async getGoodsInfo() {
    const [err, info] = await getGoodsInfoApi({
      id: this.data.goodId
    })
    if (err) return
    this.setData({
      goodInfo: info
    })
  },

  submitHandle() {
    if (this.data.cartId) {
      this.clickAddCart()
      return
    }
    if (this.data.sampleName.trim() === '') {
      wx.showToast({
        title: '请输入样品名称',
        icon: 'none'
      })
      return
    }

    const list = []
    for (let i = 0; i < this.data.tabCount; i++) {
      const child = this.selectComponent('#method-item' + i)

      if (child.data.childResult.length === 0 || child.data.sampleNumber.trim().length === 0) {
        wx.showModal({
          title: '提示',
          content: `样品${i + 1}还没有进行样品编号填写/检测项目请您完善样品检测信息`,
          showCancel: false,
          confirmColor: '#0671CB',
          confirmText: '好的',
          complete: (res) => {}
        })
        return
      }
      list.push({
        sampleNumber: child.data.sampleNumber,
        methodResult: child.data.childResult,
        countPrice: child.data.countPrice
      })
    }
    console.log(list, '====')
    // console.log([{ goodId: '', sampleName: '', sampleList: list }])

    wx.setStorageSync('confirmPrevData', [
      {
        goodId: this.data.goodId,
        sampleName: this.data.sampleName,
        sampleList: list,
        totalPrice: this.data.totalPrice
      }
    ])

    const entrustPopup = this.selectComponent('#entrust-popup')
    entrustPopup.showPopup()
  },

  async clickAddCart() {
    if (this.data.sampleName.trim() === '') {
      wx.showToast({
        title: '请输入样品名称',
        icon: 'none'
      })
      return
    }

    const list = []
    for (let i = 0; i < this.data.tabCount; i++) {
      const child = this.selectComponent('#method-item' + i)

      if (child.data.childResult.length === 0 || child.data.sampleNumber.trim().length === 0) {
        wx.showModal({
          title: '提示',
          content: `样品${i + 1}还没有进行样品编号填写/检测项目请您完善样品检测信息`,
          showCancel: false,
          confirmColor: '#0671CB',
          confirmText: '好的',
          complete: (res) => {}
        })
        return
      }
      list.push({
        sampleNum: child.data.sampleNumber,
        methodIds: child.data.childResult
      })
    }
    console.log(list, '====')
    const [existsErr, exists] = await existsInCartApi({ productId: this.data.goodId })
    if (existsErr) return
    if (exists && !this.data.cartId) {
      wx.showModal({
        title: '提示',
        content:
          '购物车已经有该样品了，添加后将会更新最新填写的样品，检测指标和方法，您确定要添加吗？',
        complete: async (res) => {
          if (res.confirm) {
            const param = {
              productId: this.data.goodId,
              sampleName: this.data.sampleName,
              methodList: list,
              cartId: this.data.cartId
            }
            const [err] = await addShoppingCartApi(param)
            if (err) return
            wx.showToast({
              title: this.data.cartId ? '已更新购物车' : '已添加购物车',
              icon: 'none'
            })
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/cart/cart'
              })
            }, 1000)
          }
        }
      })
    } else {
      const param = {
        productId: this.data.goodId,
        sampleName: this.data.sampleName,
        methodList: list,
        cartId: this.data.cartId
      }
      const [err] = await addShoppingCartApi(param)
      if (err) return
      wx.showToast({
        title: this.data.cartId ? '已更新购物车' : '已添加购物车',
        icon: 'none'
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/cart/cart'
        })
      }, 1000)
    }
  },

  /**
   * 跳转确认订单页面
   */
  jumpConfirm() {
    wx.navigateTo({
      url: `/pages/confirmOrder/confirmOrder`
    })
  },

  /**
   * 点击减少按钮
   */
  minusHandle() {
    wx.showModal({
      title: '提示',
      content: `您的样品${this.data.tabCount}已经完善好了检测信息确定要删除吗？`,
      confirmColor: '#0671CB',
      complete: (res) => {
        if (res.confirm) {
          let tabState = this.data.tabState
          if (this.data.tabCount === tabState + 1) {
            --tabState
          }
          this.setData(
            {
              tabCount: --this.data.tabCount,
              tabState
            },
            () => {
              this.computedPrice()
            }
          )
        }
      }
    })
  },

  /**
   * 点击增加按钮
   */
  plusHandle() {
    // const lastSample = this.selectComponent('#method-item' + (this.data.tabCount - 1))
    const currentSample = this.selectComponent('#method-item' + this.data.tabState)
    console.log(currentSample.data)
    // debugger
    if (
      currentSample.data.childResult.length === 0 ||
      currentSample.data.sampleNumber.trim().length === 0
    ) {
      wx.showModal({
        title: '提示',
        content: `该样品还没有进行样品名称填写/编号填写/检测项目请您完善样品检测信息`,
        showCancel: false,
        confirmColor: '#0671CB',
        confirmText: '好的',
        complete: (res) => {}
      })
      return
    }
    this.data.tabCount++
    this.setData(
      {
        tabCount: this.data.tabCount
      },
      () => {
        this.setData({
          tabState: this.data.tabCount - 1
        })
      }
    )
  },

  // 点击切换样品1、2、3
  tabChange(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      tabState: index
    })
  },

  computedPrice() {
    let count = 0
    for (let i = 0; i < this.data.tabCount; i++) {
      const child = this.selectComponent('#method-item' + i)
      count = count + child.data.countPrice
    }
    this.setData({
      totalPrice: Number(count) / 100
    })
  },

  /**
   * 获取购物车详情
   */
  async getCartDetail() {
    const [err, data] = await getCartDetailApi({ id: this.data.cartId })
    if (err) return

    this.setData(
      {
        cartDetail: data,
        tabCount: data.sampleList.length,
        sampleName: data.sampleName
      },
      () => {
        for (let i = 0; i < this.data.tabCount; i++) {
          // const { childResult, countPrice } = copyData
          const { normList, sampleNum } = this.data.cartDetail.sampleList[i]
          const selectList = normList.reduce((pre, cur) => {
            const select = cur.methodList.filter((item) => item.select === true)
            return [...pre, ...select]
          }, [])
          const childResult = selectList.map((item) => item.id.toString())
          const countPrice = selectList.reduce((pre, cur) => pre + Number(cur.price) * 100, 0)
          const curComp = this.selectComponent('#method-item' + i)
          curComp.setData({ childResult, countPrice: countPrice, sampleNumber: sampleNum }, () => {
            this.computedPrice()
          })
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { goodId, cartId } = options
    this.setData(
      {
        goodId,
        cartId
      },
      () => {
        this.getGoodsInfo()
        if (this.data.cartId) {
          this.getCartDetail()
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
